package main

import (
	"fmt"
	"io"
	"log"
	"net/http"
	"os"
	"os/signal"
	"syscall"
	"time"
)

/**
模拟真实下游服务器
*/
func main() {
	// 启动两个服务
	rs1 := &RealServ{Addr: "127.0.0.1:2003"}
	rs1.Run()
	rs2 := &RealServ{Addr: "127.0.0.1:2004"}
	rs2.Run()

	quit := make(chan os.Signal)
	signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
	<-quit
}

/**
下游服务器
*/
type RealServ struct {
	Addr string
}

/**
启动服务
*/
func (rs *RealServ) Run() {
	log.Print("Starting HttpServ at " + rs.Addr)
	mux := http.NewServeMux()
	mux.HandleFunc("/", rs.HelloHandler)
	mux.HandleFunc("/base/error", rs.ErrorHandler)
	server := &http.Server{
		Addr:         rs.Addr,
		WriteTimeout: time.Second * 3,
		Handler:      mux,
	}
	go func() {
		log.Fatal(server.ListenAndServe())
	}()
}

/**
Hello路由
*/
func (rs *RealServ) HelloHandler(rw http.ResponseWriter, req *http.Request) {
	// 请求路径
	upath := fmt.Sprintf("http://%s%s\n", rs.Addr, req.URL.Path)

	realIP := fmt.Sprintf("RemoteAddr=%s,X-Forwarded-For=%v,X-Real-IP=%v\n",
		req.RemoteAddr, req.Header.Get("X-Forwarded-For"), req.Header.Get("X-Real-Ip"))

	io.WriteString(rw, upath)
	io.WriteString(rw, realIP)
}

/**
错误路由
*/
func (rs *RealServ) ErrorHandler(rw http.ResponseWriter, req *http.Request) {
	upath := "error handler"
	rw.WriteHeader(http.StatusInternalServerError)
	io.WriteString(rw, upath)
}
